# -*- coding: utf-8 -*-

import json
from settings import render
from mako.template import Template
import web


def build_json(result=True,
               count=0,
               **kws):
    return json.dumps(
                      kws.update({"result":result,
                                  "count":count}),
                      encoding="utf8")

def response(text, type):
    web.header('Content-Type', type or 'text/html')
    return Template(text).render()

def json_response(**kws):
    return response(build_json(**kws), "text/json")

def json_response_ok(**kws):
    return response(build_json(result=True, **kws), "text/json")

def json_response_fail(**kws):
    return response(build_json(result=False, **kws), "text/json")

def setval(inst, name, value):
    if isinstance(inst, dict):
        inst[name] = value
    else:
        setattr(inst, name, value)

class jsonresp(object):
    def __init__(self, *args):
        self.args = args

    def __call__(self, func):
        def _(*args, **kwargs):
            ret = func(*args, **kwargs)
            if not isinstance(ret, list) and not isinstance(ret, tuple):
                ret = (ret,)
            print "json result: ", zip(self.args, ret)
            return response(json.dumps(dict(zip(self.args, ret)), encoding="utf8"), "text/json")
        return _

class bind(object):
    def __init__(self, clz, *args, **kwargs):
        self.clz = clz
        self.args = args
        self.kwargs = kwargs

    def __call__(self, func):
        def _(req, *args, **kwargs):
            inst = self.clz()
            data = web.input()

            for arg in self.args:
                v = data.get(arg, None)
                setval(inst, arg, v)
            for arg, default_v in self.kwargs.items():
                v = data.get(arg, None) or default_v
                setval(inst, arg, v)

            return func(req, inst, *args, **kwargs)
        return _

if __name__ == "__main__":
    print json_response(data=[1], result=True)
